#!/bin/bash
#===============================================================================
# Copyright 2011 zod.yslin
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 
# Author: zod.yslin
# Email: 
# File Name: demo.sh
# Description: 
#   Process substitution is supported on systems that support named pipes (fifos) 
#   or the /dev/fd method of naming open files. It takes the form of
#       <(list)
#   or
#       >(list)
#   有名管道可以将无关的进程联系起来，而无名的普通管道一般只能将父子进程联系起来——
#   除非你很努力地去尝试——当然也能联系两个无关进程。
#   有名管道是严格单向的，尽管在一些系统中无名管道是双向的
#   Pipes allow separate processes to communicate without having been designed 
#   explicitly to work together. 
#   This allows tools quite narrow in their function to be combined in complex ways.
# Edit History: 
#   2011-10-04    File created.
#===============================================================================

#The ls program produces a list of files in the current directory, 
#while the grep program reads the output of ls and prints only those lines containing the string demo.
echo `ls | grep demo`   # unnamed pipe

#named pipe, which is sometimes called a FIFO. 
#FIFO stands for “First In, First Out” and refers to the property that the order of bytes going in is the same coming out.
#% ls -l fifo1
#prw-r--r--   1 zod  users    0 Jan 22 23:11 fifo1|
#The p in the leftmost column indicates that fifo1 is a pipe.

#On older Linux systems, named pipes are created by the mknod program, 
#usually located in the /etc directory. 
#On more modern systems, mkfifo is a standard utility. 
#The mkfifo program takes one or more file names as arguments for this task and creates pipes with those names. 
#For example, to create a named pipe with the name pipe1 give the command:
if [ ! -p pipe ] ; then
   mkfifo pipe
fi

#In one virtual console1, type:
#ls -l > pipe
#and in another type:
#cat < pipe

#Similarly, giving >(commands) results in Bash naming a temporary pipe, which the commands inside the parenthesis read for input.
cat <(ls -l)

#whether two directories contain the same file names, run the single command:
cmp <(ls ../) <(ls .)

#counts the number of occurrences of a, p and b in the output of ls and writes this information to three separate files
ls .. | tee >(grep a | wc >a.count) \
    >(grep p | wc >p.count) \
    | grep b | wc >b.count

#Command substitutions can even be nested
cat <(cat <(cat <(ls -l)))
